<template>
	<view class="AIChatCreate" :style="{ height: webStyle.height }">
		<view class="title-box" :style="{ 'padding-top': inf0Pt + 'vh' }">
			<image class="back" @click="back" :src="imgPath + 'AICont/back-arrow.svg'" mode="widthFix"></image>
			<view class="title">AI智能体创建</view>
			<view class="back"></view>
		</view>
		<view class="residue-tips" v-if="0">
			剩余脚本生成
			<text style="color: #f00">8</text>
			次
		</view>
		<scroll-view class="main-form" :scroll-y="true" :scroll-with-animation="false" :scroll-into-view="scrollViewId">
			<template v-if="mainTabbar[mainTabbarInd] && mainTabbar[mainTabbarInd].val">
				<view class="form-item" v-for="(item, index) in mainTabbar[mainTabbarInd].val" :id="'item_' + item.myId" :key="item.menuId">
					<view class="label">
						<view class="text">{{ item.name }}</view>
						<view class="subText"></view>
					</view>
					<view v-if="item.categoryType == 'input'" class="box input-box">
						<!-- #ifdef MP-WEIXIN -->
						<input class="text" style="white-space: pre-wrap" type="text" placeholder-class="nac" @focus="(evnet) => replaceFocus(evnet, item, index)" @input.native="(evnet) => replaceInput_wx(evnet, item, index)" :value="item.val" :placeholder="item.prompt || '请输入' + item.name" />
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<input class="text" style="white-space: pre-wrap" type="text" placeholder-class="nac" @focus="(evnet) => replaceFocus(evnet, item, index)" @input="(evnet) => replaceInput_web(evnet, item, index)" :value="item.val" :placeholder="item.prompt || '请输入' + item.name" />
						<!-- #endif -->
					</view>
					<view v-if="item.categoryType == 'textarea'" class="box textarea-box">
						<textarea
							class="text"
							style="white-space: pre-wrap"
							placeholder-class="nac"
							@focus="(evnet) => replaceFocus(evnet, item, index)"
							@input="(evnet) => replaceInput_web(evnet, item, index)"
							@input.native="(evnet) => replaceInput_wx(evnet, item, index)"
							:value="item.val"
							:maxlength="item.maxlength || item.maxlength === 0 ? item.maxlength : -1"
							:placeholder="item.prompt || '请输入' + item.name"
						></textarea>
						<view class="num" v-if="(item.maxlength || item.maxlength === 0 ? item.maxlength : -1) != -1">{{ item.val.length }} / {{ item.maxlength }}</view>
					</view>
					<picker v-if="['select', 'radio'].includes(item.categoryType)" @change="(evnet) => bindPickerChange(evnet, item, index)" :value="item.ind" :range="item.catalogList" range-key="name">
						<view class="box select-box">
							<view class="text" v-if="item.ind != -1">{{ item.catalogList[item.ind].name }}</view>
							<view class="text nac" v-else>{{ "请选择分类" }}</view>
							<view class="right">
								<image class="icon" :src="imgPath + 'AICont/arrow.svg'" mode="widthFix"></image>
							</view>
						</view>
					</picker>
				</view>
				<view class="ios-padding-bottom"></view>
			</template>
		</scroll-view>
		<view class="f">
			<view class="submit" @tap="submit">生成智能体</view>
		</view>
		<LoginDialog ref="LoginDialog" :show="LoginDialogShow" @successFn="loginDialogShowSucc" @changeShow="changeLoginDialogShow" style="z-index: 999"></LoginDialog>
	</view>
</template>

<script>
import { tools } from "../../utils/util";
import * as api from "@/api/createVideo.js";

let replaceInputWatchTimer = null;
export default {
	name: "AIChatCreate",
	data() {
		return {
			imgPath: tools.imgPath,
			inf0Pt: 0,
			systemInfo: {},
			webStyle: {
				height: ""
			},
			LoginDialogShow: false,
			pageInfo: null,
			mainTabbarInd: 0,
			mainTabbar: [],
			scrollViewId: ""
		};
	},
	methods: {
		// 跳转页面
		toPage(path, type = "navigateTo") {
			uni[type]({
				url: path
			});
		},
		// 监听登录弹出层显示
		changeLoginDialogShow(val) {
			this.LoginDialogShow = val;
		},
		// 登陆成功数据刷新
		loginDialogShowSucc() {
			this.getData();
		},
		// 生成语料
		async submit() {
			if (replaceInputWatchTimer) return;
			let currMainTabbar = this.mainTabbar[this.mainTabbarInd];
			let nextFlag = true;
			let userInput = currMainTabbar.val.reduce((p, e, i) => {
				if (e.isRequired && e.val === "") nextFlag = false;
				p[e.signSn] = `${e.val}${e.signSn3 ? "{{" + e.signSn3 + "}}" : ""}`;
				return p;
			}, {});
			if (!nextFlag) return tools.easyToast("请补充以上内容！");
			uni.showLoading({
				title: "请稍后..."
			});
			let res = await api.createAIChat({
				agentNameCn: currMainTabbar.val.find((e) => e.myId == 0).val,
				agentNameEn: "",
				agentDescription: currMainTabbar.val.find((e) => e.myId == 3).val,
				agentInstruct: currMainTabbar.val.find((e) => e.myId == 1).val,
				agentChatCfgVoList: [
					{
						content: currMainTabbar.val.find((e) => e.myId == 2).val
					}
				],
				agentUseType: "chat"
			});
			uni.hideLoading();
			if (!res || res.data) return tools.easyToast("生成失败，请重试！");
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2];
			if (prevPage) {
				prevPage.$vm.getLeftData();
			}
			this.back();
		},
		// 获取数据
		getData() {
			this.mainTabbar = [
				{
					val: [
						{
							categoryType: "input",
							ind: 0,
							val: "",
							signSn3: "",
							prompt: "请输入智能体中文名称",
							name: "中文名称",
							menuId: tools.createID(),
							myId: 0,
							isRequired: true
						},
						{
							categoryType: "textarea",
							ind: 0,
							val: "",
							signSn3: "",
							prompt:
								"详细描写设定信息，示例:\n\n# 人设身份\n你是旅游达人李华，一个充满热情和乐观精神的旅游专家，拥有丰富的旅游经验和独特的见解。\n\n# 能力&任务\n你熟悉各类旅游目的地和行程规划，能提供个性化的旅游建议和服务，让用户享受到更美好的旅程。\n\n# 输出约束\n你的回复将充满正能量，积极向上，符合旅游达人的形象",
							name: "智能体的设定",
							menuId: tools.createID(),
							myId: 1,
							isRequired: true
						},
						{
							categoryType: "textarea",
							ind: 0,
							val: "",
							signSn3: "",
							prompt: "请输入智能体开场白",
							name: "开场白",
							menuId: tools.createID(),
							maxlength: 100,
							myId: 2,
							isRequired: true
						},
						{
							categoryType: "textarea",
							ind: 0,
							val: "",
							signSn3: "",
							prompt: "简单介绍你的智能体，让大家更加了解如何与TA对话。",
							name: "简介",
							menuId: tools.createID(),
							maxlength: 100,
							myId: 3,
							isRequired: true
						}
					]
				}
			];
		},
		// 监听input事件
		replaceInput_wx(event, item, index) {
			// #ifdef MP-WEIXIN
			this.replaceInput(event, item, index);
			// #endif
		},
		// 监听input事件
		replaceInput_web(event, item, index) {
			// #ifdef H5
			this.replaceInput(event, item, index);
			// #endif
		},
		// 监听input事件
		async replaceInput(event, item, index) {
			if (replaceInputWatchTimer) {
				clearTimeout(replaceInputWatchTimer);
			}
			replaceInputWatchTimer = setTimeout(() => {
				if (this.mainTabbar[this.mainTabbarInd].val[index].val === event.target.value) return;
				this.mainTabbar[this.mainTabbarInd].val[index].val = event.target.value.slice(0, item.maxlength);
				console.log("文案改变", this.mainTabbar[this.mainTabbarInd].val[index].val);
				replaceInputWatchTimer = null;
			}, 688);
		},
		// 监听input事件
		async replaceFocus(event, item, index) {
			this.scrollViewId = "item_" + item.myId;
			if (this.scrollViewId != "") {
				await new Promise((sleep) => setTimeout(sleep, 1886));
				this.scrollViewId = "";
			}
		},
		// picker改变事件
		bindPickerChange(event, item, index) {
			let ind = event.detail.value;
			item = this.mainTabbar[this.mainTabbarInd].val[index];
			item.ind = ind;
			item.val = item.catalogList[ind]?.name ?? "";
			item.signSn3 = item.catalogList[ind]?.signSn ?? "";
		},
		// 回退
		back() {
			let pages = getCurrentPages();
			if (pages.length > 1) {
				uni.navigateBack({
					delta: 1
				});
			} else {
				uni.setStorageSync("toHome", {
					footerBarListAc: 1
				});
				uni.reLaunch({
					url: "/pages/index/index"
				});
			}
		},
		// 获取页面参数
		initPageInfo(opt) {
			let pageInfo = uni.getStorageSync("AIContInfo");
			this.pageInfo = pageInfo;
			uni.removeStorageSync("AIContInfo");
		},
		// 获取系统info
		initSystemInfo(isUpdate = true) {
			const that = this;
			return new Promise((resolve, reject) => {
				uni.getSystemInfo({
					success(payload) {
						if (isUpdate) {
							that.systemInfo = payload;
							that.webStyle.height = `${that.systemInfo.windowHeight}px`;
							console.log("initSystemInfo", that.systemInfo);
							switch (that.systemInfo.uniPlatform) {
								case "web":
									that.inf0Pt = 4.5;
									break;
								case "app":
									that.inf0Pt = 4.5;
									break;
								case "mp-weixin":
									that.inf0Pt = 4.5;
									break;
							}
						}
						resolve(payload);
					}
				});
			});
		}
	},
	onLoad(opt) {
		this.initPageInfo(opt);
		this.getData();
	},
	created() {
		this.initSystemInfo();
	}
};
</script>

<style lang="scss">
::-webkit-scrollbar {
	width: 0vw !important;
	height: 0vw !important;
	display: none;
}

.AIChatCreate {
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	// background: radial-gradient(#034748 0%, #010c1f 100%);
	background: radial-gradient(#117d62 0%, #010c1f 100%);
	box-sizing: border-box;
	padding: 3vw;
	display: flex;
	flex-direction: column;

	.title-box {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.back {
			width: 6vw;
		}

		.title {
			font-size: 36rpx;
			font-weight: 400;
			color: rgba(255, 255, 255, 1);
		}
	}

	.residue-tips {
		margin: 6vw 3vw;
		font-size: 36rpx;
		font-weight: 400;
		color: rgba(243, 173, 51, 1);
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 2vw 0vw;
		background: linear-gradient(90deg, rgba(247, 225, 111, 0) 0.17%, rgba(252, 219, 96, 0.47) 51.66%, rgba(247, 225, 111, 0) 100%);
	}

	.main-form {
		flex: 1;
		overflow: auto;

		.form-item {
			margin: 6vw 0vw;

			.label {
				font-weight: 400;
				color: rgba(255, 255, 255, 1);
				display: flex;
				align-items: end;

				.text {
					font-size: 36rpx;
					margin-right: 2vw;
				}

				.subText {
					font-size: 24rpx;
				}
			}

			.box {
				margin-top: 2.5vw;
				border-radius: 3vw;
				background: rgba(255, 255, 255, 0.08);
				border: 1px solid rgba(56, 108, 92, 1);
				backdrop-filter: blur(26px);
				min-height: 10vw;
				box-sizing: border-box;
				padding: 1vw 2.5vw;

				.text {
					font-size: 28rpx;
					font-weight: 400;
					color: rgba(255, 255, 255, 1);

					&.nac {
						color: rgba(255, 255, 255, 0.46);
					}
				}

				&.select-box {
					width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.right {
						.icon {
							width: 1.68vw;
						}
					}
				}

				&.input-box {
					display: flex;
					align-items: center;
					height: 100%;
					width: 100%;

					.text {
						width: 100%;
					}
				}

				&.textarea-box {
					height: 68vw;
					overflow: auto;
					position: relative;

					.text {
						width: 100%;
						height: 100%;
						overflow: auto;
					}
					.num {
						position: absolute;
						bottom: 1vw;
						right: 1vw;
						font-size: 20rpx;
						font-weight: 400;
						color: rgba(255, 255, 255, 0.46);
					}
				}
			}
		}
	}

	.f {
		// height: 52vw;
		box-sizing: border-box;
		padding: 10vw 0vw;

		.submit {
			width: 100%;
			opacity: 1;
			border-radius: 10px;
			background: rgba(0, 153, 127, 1);
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 36rpx;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
			padding: 2.5vw 0vw;
		}
	}
}
</style>
